package com.tangcheng.adapter.db.mybatis.plugin.sensitive.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

@Service
@Slf4j
public class AESBase64EncryptionAlgorithm implements IEncryptionAlgorithm {

    private SecretKeySpec AES_PASSWORD;

    @Value("${sensitive.field.encryption.aesSecret}")
    private String aesSecret;

    @Override
    public String getAesSecret() {
        return aesSecret;
    }

    @Override
    public String encrypt(String content) {
        if (StringUtils.isEmpty(content)) {
            return content;
        } else {
            try {
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(1, getSecretKey(this.aesSecret));
                byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
                return Base64.getEncoder().encodeToString(encrypted);
            } catch (Exception e) {
                log.error("加密失败 {}", e.getMessage());
                return content;
            }
        }
    }

    @Override
    public String decrypt(String content) {
        if (StringUtils.isBlank(content)) {
            return content;
        } else {
            content = content.replaceAll("[\\t\\n\\r]", "");

            try {
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(2, getSecretKey(this.aesSecret));
                byte[] base64Data = Base64.getDecoder().decode(content);
                byte[] original = cipher.doFinal(base64Data);
                String originalString = new String(original, StandardCharsets.UTF_8);
                return originalString;
            } catch (Exception e) {
                log.error("解密失败 {}", e.getMessage());
                return content;
            }
        }
    }

    private SecretKeySpec getSecretKey(String password) throws Exception {
        if (AES_PASSWORD != null) {
            return AES_PASSWORD;
        } else {
            try {
                byte[] keyBytes = Arrays.copyOf(password.getBytes("ASCII"), 16);
                AES_PASSWORD = new SecretKeySpec(keyBytes, "AES");
                return AES_PASSWORD;
            } catch (Exception e) {
                log.error("加密秘钥失败 ", e);
                throw new Exception("加密秘钥失败" + e.getMessage());
            }
        }
    }


}